package com.authsphere.springboot.starter.plugin.account.bind;

import com.authsphere.plugin.api.AuthSphereAfterPlugin;
import com.authsphere.security.account.api.bind.AccountBindAfterPlugin;
import com.authsphere.security.account.api.bind.AccountBindService;
import com.authsphere.security.account.api.bind.AccountBindTempTokenRepository;
import com.authsphere.security.account.api.bind.BindingExecutor;
import com.authsphere.security.account.common.bind.PersistentTokenBasedAccountBindService;
import com.authsphere.security.account.common.config.SecurityAccountConfig;
import com.authsphere.security.account.redis.bind.RedisAccountBindTempTokenRepository;
import com.authsphere.springboot.starter.plugin.account.AccountPluginConfiguration;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/26 09:06
 **/
@Configuration
@AutoConfigureAfter(AccountPluginConfiguration.class)
public class AccountBindAfterPluginConfiguration {

    @Bean
    @ConditionalOnBean(AccountBindService.class)
    public AuthSphereAfterPlugin accountBindAfterPlugin(final AccountBindService accountBindService) {
        return new AccountBindAfterPlugin(accountBindService);
    }

    @Bean
    @ConditionalOnBean(value = {BindingExecutor.class, AccountBindTempTokenRepository.class})
    public AccountBindService accountBindService(
            final BindingExecutor bindingExecutor,
            final ObjectProvider<SecurityAccountConfig> configProvider,
            final AccountBindTempTokenRepository tokenRepository) {
        SecurityAccountConfig config = configProvider.getIfAvailable(SecurityAccountConfig::new);
        return new PersistentTokenBasedAccountBindService(bindingExecutor, config.getBindAccountConfig(), tokenRepository);
    }

    @Bean
    @ConditionalOnBean(StringRedisTemplate.class)
    public AccountBindTempTokenRepository redisAccountBindTempTokenRepository(final StringRedisTemplate stringRedisTemplate) {
        return new RedisAccountBindTempTokenRepository(stringRedisTemplate);
    }
}
